#include "FileSystem.h"

FileSystem::FileSystem()
{
	fileName = NULL;
	content = NULL;
	length = 0;
};

FileSystem::FileSystem(char *fileName)
{
	setFileName(fileName);
	content = NULL;
	length = 0;
};

FileSystem::~FileSystem()
{
	SAFE_DEL(fileName);
	SAFE_DEL(content);
};

void FileSystem::setFileName(char *_fileName)
{
	fileName = new char[strlen(_fileName) + 1];
	strcpy(fileName, _fileName);
};

char* FileSystem::getContentFile()
{
	return content;
};

int FileSystem::getLengthFile()
{
	return length;
};

void FileSystem::WriteFile(char *data)
{
	ofstream myFile(fileName);
	if (myFile.is_open()) {
		for (int i = 0; i < (int)strlen(data); i++) {
			myFile << data[i];
		}
		myFile.close();
	}
	else {
		cout << "Unable to open file ..." << endl;
	}
};

void FileSystem::ReadFile()
{
	ifstream myFile(fileName);
	char ch;
	int i = 0;

	if (myFile.is_open()) {
		int begin = (int)myFile.tellg();
		myFile.seekg (0, ios::end);
		int end = (int)myFile.tellg();
		myFile.seekg (0, ios::beg);
		length = end - begin;
		content = new char[length + 1];

		while (myFile.good()) {
			ch = myFile.get();
			content[i++] = ch;
		}

		myFile.close();
	}

	else {
		cout << "Unable to open file ..." << endl; 
	}
};

void FileSystem::WriteFileBin(char *data)
{
	ofstream myFile(fileName, ios::out | ios::binary);
	if (myFile.is_open()) {
		myFile.write(data, (int)strlen(data));
		myFile.close();
	}
	else {
		cout << "Unable to open file ..." << endl;
	}
};

void FileSystem::ReadFileBin()
{
	ifstream::pos_type size;

	ifstream myFile (fileName, ios::in | ios::binary | ios::ate);
	
	if (myFile.is_open())
	{
		size = myFile.tellg();
		length = (int)size;
		content = new char[length];
		myFile.seekg (0, ios::beg);
		myFile.read (content, length);
		myFile.close();
	}

	else cout << "Unable to open file";
};